package com.cloud.applet.util;

import com.cloud.applet.common.constant.JwtProperties;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 创建一个token
     * @param jwtInfo
     * @return
     */
    public String cerateToken(JwtInfo jwtInfo){
        //获取的jwtBuilder
        JwtBuilder builder = Jwts.builder();

        //设置头部信息
        builder.setHeaderParam("alg","HS256");
        builder.setHeaderParam("typ","JWT");

        //设置载荷信息
        builder.setIssuer("evans");
        builder.setSubject("practice");
        builder.setIssuedAt(new Date());//发布时间
        builder.setExpiration(new Date(new Date().getTime()+1800000));
        //设置私有字段  jwtBuilder.claim("id","1");
        builder.claim("userId",jwtInfo.getId());

        //这是签名
        builder.signWith(SignatureAlgorithm.HS256,"faker");

        String compact = builder.compact();
        return compact;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public Claims verifyAndGetClaimsByToken(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token);
        return claimsJws.getBody();
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    public Integer getUserId(String token){
        Claims claims = this.verifyAndGetClaimsByToken(token);
        Integer userId = (Integer) claims.get(jwtProperties.getUserId());
        return userId;
    }
}
